package cn._2dland.http.method.multiparts;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

/**
 * 文件数据块
 * 
 * @author deadblue
 */
public class FilePart extends Part {
	/** 字节组 */
	private byte[] buf = null;
	/** 文件名 */
	private String fileName = null;
	/** 数据类型 */
	private String contentType = null;

	/** 缺省文件名 */
	private static final String DEFAULT_FILE_NAME = "noname";
	/** 缺省内容类型 */
	private static final String DEFAULT_CONTENT_TYPE = "application/octet-stream";

	public FilePart(String name) {
		this(name, null, null);
	}
	public FilePart(String name, String contentType) {
		this(name, contentType, null);
	}
	public FilePart(String name, String contentType, String fileName) {
		super(name);
		this.fileName = fileName;
		this.contentType = contentType;
	}

	/**
	 * 设置文件名
	 * @param name - 文件名
	 */
	public void setFileName(String name) {
		fileName = name;
	}
	/**
	 * 设置内容类型
	 * @param type
	 */
	public void setContentType(String type) {
		this.contentType = type;
	}

	/**
	 * 读取文件
	 * @param fullFileName - 文件名
	 */
	public void readFile(String fullFileName) throws Exception {
		readFile(new File(fullFileName));
	}
	/**
	 * 读取文件
	 * @param file - 文件对象
	 */
	public void readFile(File file) throws Exception {
		if(fileName == null)
			fileName = file.getName();
		readStream(new FileInputStream(file), true);
	}

	/**
	 * 读取流
	 * @param stream 输入流
	 * @param closeAfterRead 读取完毕是否关闭输入流
	 */
	public void readStream(InputStream stream, boolean closeAfterRead) throws Exception {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		for(int b=0; (b=stream.read())>=0; ){
			baos.write(b);
		}
		baos.flush();
		buf = baos.toByteArray();
		baos.close();

		if(closeAfterRead)
			stream.close();
	}

	/**
	 * 读取字节组
	 * @param src - 来源字节组
	 */
	public void readBytes(byte[] src) {
		// 从原字节组复制
		buf = new byte[src.length];
		System.arraycopy(src, 0, buf, 0, src.length);
	}

	@Override
	public byte[] getBytes() {
		ByteArrayOutputStream ba = new ByteArrayOutputStream();
		try {
			// 防止空值
			if(contentType == null) contentType = DEFAULT_CONTENT_TYPE;
			if(fileName == null) fileName = DEFAULT_FILE_NAME;

			// 构造头部字符串
			StringBuffer sb = new StringBuffer();
			sb.append("Content-Disposition: form-data; ").append("name=\"").append(name).append("\"; ")
				.append("filename=\"").append(fileName).append("\"").append(CRLF)
				.append("Content-Type: ").append(contentType).append(CRLF).append(CRLF);
			// 写入输出流
			ba.write(sb.toString().getBytes(charset));
			ba.write(buf);
			ba.write(CRLF.getBytes());
		}
		catch (Exception e) { e.printStackTrace(); }
		return ba.toByteArray();
	}
}